package com.harmontronics.hanma.paas.paas.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.harmontronics.hanma.paas.paas.token.ComposeTokenKit;
import com.harmontronics.hanma.paas.paas.token.MosTokenKit;
import com.harmontronics.hanma.paas.paas.token.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 *
 *
 * @ClassName : BaseEntityHandler
 * @Description :
 * @Author : Alex
 * @Date: 2020-06-29 17:04
 */
@Slf4j
@Component
public class BaseEntityHandler implements MetaObjectHandler {

    @Autowired
    private ComposeTokenKit composeTokenKit;

    @Autowired
    private MosTokenKit mosTokenKit;

    @Value("${mos.oss.enabled:false}")
    private Boolean mosEnabled;

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createBy", String.class, getCurrentUserName());
        this.strictInsertFill(metaObject, "modifyDate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "modifyBy", String.class, getCurrentUserName());

    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("modifyDate", LocalDateTime.now(),metaObject);
        this.setFieldValByName("modifyBy", getCurrentUserName(),metaObject);
    }

    public String getCurrentUserName(){
        if(mosEnabled != null && mosEnabled){
            return mosTokenKit.getUserInfo().getUserName();
        }

        UserInfo userInfo = composeTokenKit.getUserInfo();
        if(userInfo == null){
            return "";
        }
        return userInfo.getUserName();
    }
}
